package com.pan.insist.controller.webSocket;

import lombok.extern.log4j.Log4j2;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * <p>
 *     服务器端推送消息
 * </p>
 *
 * @author kaiji
 * @since 2020/2/7 21:17
 */
@Log4j2
@Controller
public class SocketServerController {

    // 记录当前连接数
    private AtomicInteger count = new AtomicInteger();
    /** 记录当前SocketServer对象 **/ 
    private static Set<SocketServerController> list = new CopyOnWriteArraySet<>();

    @GetMapping("/socket/index")
    public String index() {
        return "socket/index";
    }

    /**
     * 接收客户端的发送过来的消息
     *
     * @param msg
     *      客户发送来的消息, 可以是对象
     * @return  返回消息
     */
    @MessageMapping("/hello")
    @SendTo("/topic/samuel")
    public String receiveMsg(String msg) {
        //与某个客户端的连接会话，需要通过它来给客户端发送数据
        count.getAndIncrement();
        list.add(this);
        log.info("当前连接人数为：{}", count.intValue());
        log.info("接收到的消息：{}", msg);
        return "hello websocket, my name is samuel! i am received msg";
    }


    // @SendToUser
    public String pushMsg() {

        return null;
    }



}
